/**
 * Copyright (c) 快宝网络 kuaidihelp.com Co., Ltd. All Rights Reserved 禁止外泄以及用于其它的商业用途
 */

import React, { useState } from 'react';
import { useDispatch } from 'dva';
import { Form, Row, Col, Button, Input, Table, Popconfirm, message } from 'antd';
import PageHeaderLayout from '@/layouts/PageHeaderLayout';
import DragTable from '@/components/DragTable';
import { useDebounceFn, useAntdTable } from 'ahooks';
import { deleteAddressSort } from '@/services/automatic';
import AsyncDownLoad from '@/components/DownloadBar/AsyncDownLoad';
import AddressSortModal from './components/AddressSortModal';
import styles from './styles.less';
import UploadWithCrypto from '@/components/upload-width-crypto';

const FormItem = Form.Item;

const AddressSort = props => {
  const dispatch = useDispatch();
  const { form } = props;
  const { getFieldDecorator, validateFields, getFieldsValue } = form;
  const [selectedRow, setSelectedRow] = useState([]);
  const [selectedItem, setSelectedItem] = useState({});
  const [open, setOpen] = useState(false);
  const [uploading, setUploading] = useState(false);

  const getTableList = async ({ current, pageSize }, formData) => {
    const { list = [], pagination = {} } = await dispatch({
      type: 'automatic/getAddressSortList',
      payload: {
        page: current,
        size: pageSize,
        ...formData,
      },
    });
    return {
      list,
      total: pagination.total || 0,
    };
  };

  const { tableProps, search, loading } = useAntdTable(getTableList, {
    defaultPageSize: 20,
    defaultParams: [{ current: 1, pageSize: 20 }],
    form,
  });

  const onEdit = record => {
    setSelectedItem(record);
    setOpen(true);
  };

  const onDelete = (id = []) => {
    deleteAddressSort({ ids: JSON.stringify(id) }).then(res => {
      const { code, msg } = res || {};
      if (code == 0) {
        message.success('删除成功！');
        search.submit();
        if (id.length > 1) {
          setSelectedRow([]);
        }
      } else {
        message.error(msg);
      }
    });
  };

  const columns = [
    {
      title: '优先级',
      dataIndex: 'sort',
      key: 'sort',
      width: 120,
      align: 'center',
    },
    {
      title: '关键字',
      dataIndex: 'addr_scheme',
      key: 'addr_scheme',
      width: 370,
      align: 'left',
    },
    {
      title: '分拣线编号',
      dataIndex: 'sorting_line_code',
      key: 'sorting_line_code',
      width: 150,
      align: 'left',
    },
    {
      title: '格口号',
      dataIndex: 'codes',
      key: 'codes',
      width: 150,
      align: 'left',
    },
    {
      title: '操作',
      width: 200,
      align: 'center',
      render: (_, record) => (
        <Row type="flex" justify="space-around">
          <Col>
            <a onClick={() => onEdit(record)}>编辑</a>
          </Col>
          <Col>
            <Popconfirm title="确定删除此项？" onConfirm={() => onDelete([record.id])}>
              <a>删除</a>
            </Popconfirm>
          </Col>
        </Row>
      ),
    },
  ];

  const onSelectChange = selectedRowKeys => {
    setSelectedRow(selectedRowKeys);
  };

  const onUpLoadChange = info => {
    setUploading(true);
    if (info.file.status === 'done') {
      message.success(`${info.file.name} 上传成功`);
      search.submit();
      setUploading(false);
    } else if (info.file.status === 'error') {
      message.error(`${info.file.name} 上传失败`);
      setUploading(false);
    }
  };

  const { run: onSearch } = useDebounceFn(
    () => {
      validateFields(err => {
        if (err) return;
        search.submit();
      });
    },
    {
      wait: 300,
      leading: true,
      trailing: false,
    },
  );

  const getExportAllData = () => {
    const formValue = getFieldsValue();
    return {
      ...formValue,
      is_down: 1,
    };
  };

  return (
    <PageHeaderLayout title="地址分拣">
      <div className={styles.main}>
        <Form layout="inline" style={{ marginBottom: 24 }}>
          <Row type="flex" justify="space-between">
            <Col>
              <Row type="flex" gutter={[20, 20]}>
                <Col>
                  <Button type="primary" onClick={() => setOpen(true)}>
                    新建方案
                  </Button>
                </Col>
                <Col>
                  <UploadWithCrypto
                    action="/Api/Automation/addrScheme/upload"
                    name="file"
                    multiple={false}
                    accept=".xlsx,.xls,csv"
                    showUploadList={false}
                    onChange={onUpLoadChange}
                  >
                    <Button type="primary" icon="upload" loading={uploading}>
                      导入方案
                    </Button>
                  </UploadWithCrypto>
                </Col>
                <Col>
                  <AsyncDownLoad
                    action="/Api/Automation/addrScheme/list"
                    method="POST"
                    data={getExportAllData}
                  >
                    <Button type="primary" icon="download">
                      导出方案
                    </Button>
                  </AsyncDownLoad>
                </Col>
              </Row>
            </Col>
            <Col>
              <FormItem>
                {getFieldDecorator('key')(<Input allowClear placeholder="关键字" />)}
              </FormItem>
              <FormItem>
                {getFieldDecorator('code')(<Input allowClear placeholder="格口号" />)}
              </FormItem>
              <FormItem>
                <Button type="primary" loading={loading} onClick={onSearch}>
                  查询
                </Button>
              </FormItem>
            </Col>
          </Row>
        </Form>
        <DragTable>
          <Table
            {...tableProps}
            columns={columns}
            pagination={{
              ...tableProps.pagination,
              showQuickJumper: false,
              showSizeChanger: false,
            }}
            scroll={{ x: 800 }}
            rowKey="id"
            loading={loading}
            rowSelection={{
              selectedRowKeys: selectedRow,
              onChange: onSelectChange,
              hideDefaultSelections: true,
            }}
          />
        </DragTable>
        <AddressSortModal
          visible={open}
          record={selectedItem}
          onOK={() => {
            setOpen(false);
            search.submit();
          }}
          onCancel={() => {
            setOpen(false);
            setSelectedItem({});
          }}
        />
        {selectedRow.length > 0 && (
          <div className={styles.batchDelete}>
            <Popconfirm title="确认删除选中的方案？" onConfirm={() => onDelete(selectedRow)}>
              <a>批量删除</a>
            </Popconfirm>
          </div>
        )}
      </div>
    </PageHeaderLayout>
  );
};

export default Form.create()(AddressSort);
